package com.aduerr.v1shouyin.mvp.activity;

import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.OrderGetPosOrderLEntity;
import com.aduerr.v1shouyin.entity.SyncOrderEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.print.PrinterWrapper;
import com.aduerr.v1shouyin.unioncard.BaseUnionActivity;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.orhanobut.hawk.Hawk;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class OrderDetailActivity extends BaseUnionActivity {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_icon)
    ImageView ivIcon;
    @BindView(R.id.tv_ordermoney)
    TextView tvOrdermoney;
    @BindView(R.id.tv_state)
    TextView tvState;
    @BindView(R.id.tv_refund_total)
    TextView mTvRefundTotal;
    @BindView(R.id.tv_dingdanjine)
    TextView tvDingdanjine;
    @BindView(R.id.tv_shangjiashishou)
    TextView tvShangjiashishou;
    @BindView(R.id.tv_sahngjayouhui)
    TextView tvSahngjayouhui;
    @BindView(R.id.tv_guanfangyouhui)
    TextView tvGuanfangyouhui;
    @BindView(R.id.tv_zhifubaozhanghao)
    TextView tvZhifubaozhanghao;
    @BindView(R.id.tv_creattime)
    TextView tvCreattime;
    @BindView(R.id.tv_dingdanhao)
    TextView tvDingdanhao;
    @BindView(R.id.tv_mendain)
    TextView tvMendain;
    @BindView(R.id.tv_shouyinyuan)
    TextView tvShouyinyuan;
    @BindView(R.id.tv_beizhu)
    TextView tvBeizhu;
    @BindView(R.id.tv_refoud)
    TextView tvRefoud;
    @BindView(R.id.tv_printnote)
    TextView tvPrintnote;
    @BindView(R.id.rl_refoud)
    RelativeLayout rlrefound;
    @BindView(R.id.tv_sync)
    TextView tvSync;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.rl_refund_total)
    RelativeLayout mRlRefundTotal;
    @BindView(R.id.rl_refund_remark)
    RelativeLayout mRlRefundRemark;
    @BindView(R.id.tv_refund_beizhu)
    TextView tvRefundBeizhu;
    String strRepair;
    private OrderGetPosOrderLEntity.DataBean.ListBean data;
    //content 原来是16长度，为防止越界改为20
    private String[] content = new String[20];
    private SweetAlertDialog pDialog;
    //0：从订单列表跳过来有订单记录按钮  //1：从扫码退款列表跳过来
    private int sourceType;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void initBase() {
        super.initView();
        ButterKnife.bind(this);
        tvTitle.setText("订单详情");
        tvRight.setText("退款记录");
        data = (OrderGetPosOrderLEntity.DataBean.ListBean) getIntent().getSerializableExtra("datebean");
        strRepair = getIntent().getStringExtra("repair");
        initDate(data);
    }


    private void initDate(OrderGetPosOrderLEntity.DataBean.ListBean data) {
        if(data != null) {
            String paytype = data.getPaytype();
            String paystate = data.getPaystate();
            //收款订单和会员订单此集合一定为空，依据这个判断是否显示订单记录就行
            if(data.getOrderItemRefundList()==null || data.getOrderItemRefundList().size()==0){
                tvRight.setVisibility(View.GONE);
            }else{
                tvRight.setVisibility(View.VISIBLE);
            }
            if(paystate.equals("已退款")) {
                tvPrintnote.setVisibility(View.VISIBLE);
                tvSync.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                mRlRefundTotal.setVisibility(View.VISIBLE);
                mRlRefundRemark.setVisibility(View.VISIBLE);
                rlrefound.setVisibility(View.GONE);
            } else if(paystate.equals("部分退款")) {
                tvPrintnote.setVisibility(View.VISIBLE);
                tvSync.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                mRlRefundTotal.setVisibility(View.VISIBLE);
                mRlRefundRemark.setVisibility(View.VISIBLE);
                if(data.isPosOrder()){
                    rlrefound.setVisibility(View.VISIBLE);
                }else{
                    rlrefound.setVisibility(View.GONE);
                }
            }  else if(paystate.equals("未支付")||paystate.equals("已取消")) {
                rlrefound.setVisibility(View.GONE);
                tvPrintnote.setVisibility(View.GONE);
                tvSync.setVisibility(View.VISIBLE);
                llBottom.setVisibility(View.GONE);
                mRlRefundRemark.setVisibility(View.GONE);
            } else {//已支付
                rlrefound.setVisibility(View.VISIBLE);
                tvPrintnote.setVisibility(View.VISIBLE);
                tvSync.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                mRlRefundRemark.setVisibility(View.GONE);
            }
            if(TextUtils.equals(paytype,
                    this.getString(R.string.text_dingdan_weixin))) {
                ivIcon.setImageResource(R.drawable.img_order_wechat);
            } else if(TextUtils.equals(paytype,
                    this.getResources().getString(R.string.text_dingdan_zhifubao))) {
                ivIcon.setImageResource(R.drawable.img_order_zhifubao);
            } else if(TextUtils.equals(paytype,
                    this.getResources().getString(R.string.text_dingdan_QQqianbao))) {
                ivIcon.setImageResource(R.drawable.img_order_qq);
            } else if(TextUtils.equals(paytype,
                    this.getResources().getString(R.string.text_dingdan_shuaka))) {
                rlrefound.setVisibility(View.GONE);
                ivIcon.setImageResource(R.drawable.img_order_shuaka);
            } else if(TextUtils.equals(paytype,
                    this.getResources().getString(R.string.text_dingdan_xianjin))) {
                rlrefound.setVisibility(View.GONE);
                ivIcon.setImageResource(R.drawable.img_order_cash);
            } else if(TextUtils.equals(paytype,
                    this.getResources().getString(R.string.text_dingdan_other))) {
                ivIcon.setImageResource(R.drawable.img_order_cash);
            } else if(TextUtils.equals(paytype, "云闪付")) {
                ivIcon.setImageResource(R.drawable.img_order_ysf);
            }else if(TextUtils.equals(paytype, "数币") || TextUtils.equals(paytype, "数字人民币")) {
                ivIcon.setImageResource(R.drawable.icon_digital_cirlce_big);
            }

            //小票优化后统一使用下面的格式
            content[0] = data.getOrderid();//订单编号
            content[1] = data.getShopname();//门店
            content[2] = data.getSiteusername();//收银员
            content[3] = data.getPaytype();//支付方式
            content[4] = data.getPaystate();//支付状态
            content[5] = data.getPaytime();//支付时间
            content[6] = data.getOrdermoney();//订单金额
            content[7] = data.getRealpay();//实收金额
            content[8] = data.getRefund();//退款金额
            content[9] = data.getOrdernote();//订单备注
            content[10] = data.getRefundreason();//退款备注
            content[11] = data.getRefundtime();//退款时间
            content[12] = Hawk.get("company");//账号公司
            content[13] = data.getUseraccount();//用户账号 不一定存在
            content[14] = data.getOutorderid();//不一定存在
            content[15] = data.getSelleryouhui();//不一定存在
            content[16] = data.getYouhui();//不一定存在
            content[17] = data.getRefundusername();//不一定存在

             mTvRefundTotal.setText(data.getRefund());
            tvOrdermoney.setText(data.getOrdermoney());
            tvState.setText(data.getPaystate());
            tvDingdanjine.setText(data.getOrdermoney());
            tvShangjiashishou.setText(data.getRealpay());
            tvSahngjayouhui.setText(data.getSelleryouhui());
            tvGuanfangyouhui.setText(data.getYouhui());

            tvZhifubaozhanghao.setText(data.getUseraccount());
            tvCreattime.setText(data.getCreatetime());
            tvDingdanhao.setText(data.getOrderid());
            tvMendain.setText(data.getShopname());
            tvShouyinyuan.setText(data.getSiteusername());
            tvBeizhu.setText(data.getOrdernote() + "");
            tvRefundBeizhu.setText(data.getRefundreason());

        }
    }

    @OnClick({R.id.img_back, R.id.tv_refoud, R.id.tv_printnote, R.id.tv_sync, R.id.tv_right})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_refoud:
                // TODO: 2017/12/12 0012  退款的详情
                if(data != null) {
                    Intent intent = new Intent(OrderDetailActivity.this,
                            RefoundMoneyDetailActivity.class);
                    intent.putExtra("date", data);
                    startActivity(intent);
                    finish();
                } else {
                    ToastUtils.showToast(OrderDetailActivity.this, "信息有误!");
                    return;
                }
                break;
            case R.id.tv_printnote:
                int printpage =
                        (int) SharedPreferencesUtils.getParam(OrderDetailActivity.this,
                                "printpage", 1);
                if(printpage == 0) {
                    ToastUtils.showToast(OrderDetailActivity.this, "打印张数设置为不打印," +
                            "请先设置打印张数!!");
                    return;
                }
                if(content != null && data != null) {
                    if(content[4].equals("已付款")) {
                       PrinterWrapper.printNewOrder(printpage,false,content);
                    } else {
                        printMultiRefundText();
                    }

                }
                break;
            case R.id.tv_sync:
                syncOrder();
                break;
            case R.id.tv_right:
                Intent intent = new Intent(this, RefundMultiRecordActivity.class);
                intent.putExtra("refundRecord", data);
                startActivity(intent);
                break;
        }
    }


    private void syncOrder() {

        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("OrderID", data.getOrderid());
        APIRetrofit.getAPIService().syncOrderState(RXRequest.getXingPosParams(addParams
                , this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SyncOrderEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull SyncOrderEntity syncOrderEntity) {
                        int success = syncOrderEntity.getSuccess();
                        if(success == 1) {
                            getOrderDetail();
                        } else {
                            ToastUtils.showToast(OrderDetailActivity.this, "同步失败");
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        ToastUtils.showToast(OrderDetailActivity.this, "同步失败");
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void getOrderDetail() {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("orderid", data.getOrderid());
        APIRetrofit.getAPIService().orderGetPosOrderL(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderGetPosOrderLEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if(pDialog == null) {
                            pDialog = new SweetAlertDialog(OrderDetailActivity.this,
                                    SweetAlertDialog.PROGRESS_TYPE);
                            pDialog.getProgressHelper().setBarColor(Color.parseColor(
                                    "#005fee"));
                            pDialog.setTitleText("请稍等...");
                            pDialog.setCancelable(false);
                            pDialog.show();
                        }
                    }

                    @Override
                    public void onNext(@NonNull OrderGetPosOrderLEntity orderGetPosOrderLEntity) {
                        int success = orderGetPosOrderLEntity.getSuccess();
                        if(success == 1) {
                            initDate(orderGetPosOrderLEntity.getData().get(0).getList().get(0));
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(pDialog != null) {
                            pDialog.dismiss();
                            pDialog = null;
                        }
                        ToastUtils.showToast(OrderDetailActivity.this, "同步失败");
                    }

                    @Override
                    public void onComplete() {
                        if(pDialog != null) {
                            pDialog.dismiss();
                            pDialog = null;
                        }
                        ToastUtils.showToast(OrderDetailActivity.this, "同步成功");
                    }
                });
    }

    public void printMultiRefundText() {
        int printPage = (int) SharedPreferencesUtils.getParam(this, "printpage", 1);
        if(printPage == 0) {
            ToastUtils.showToast(this, "打印张数设置为不打印,请先设置打印张数!!");
            return;
        }
        PrinterWrapper.printMultiRefundOrderDetail(data,-1,printPage,false);
    }
}
